using System;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;

namespace XFramework
{
    [CustomEditor(typeof(CodeController), true)]
    public class CodeControllerInspector : Editor
    {
        public readonly Lazy<GUIStyle> BigTitleStyle = new Lazy<GUIStyle>(() => new GUIStyle(GUI.skin.label)
        {
            fontStyle = FontStyle.Bold,
            fontSize = 13
        });

        private CodeGenSetting setting;

        [MenuItem("GameObject/CodeGen/Add Code Controller", false, 0)]
        static void AddController()
        {
            var obj = Selection.objects.First() as GameObject;

            if (null == obj)
            {
                Debug.LogWarning("需要选择GameObject");
                return;
            }

            var controller = obj.GetComponent<CodeController>();
            if (null == controller)
            {
                obj.AddComponent<CodeController>();
            }
        }

        public CodeController codeController => target as CodeController;

        private void OnEnable()
        {
            if (string.IsNullOrEmpty(codeController.Namespace))
            {
                var setting = CodeGenSetting.Load();
                codeController.Namespace = setting.Namespace;
            }

            if (string.IsNullOrEmpty(codeController.BaseName))
            {
                var setting = CodeGenSetting.Load();
                codeController.BaseName = setting.BaseName;
            }

            if (string.IsNullOrEmpty(codeController.ScriptsFolder))
            {
                var setting = CodeGenSetting.Load();
                codeController.ScriptsFolder = setting.ScriptDir;
            }

            if (string.IsNullOrEmpty(codeController.ScriptName))
            {
                codeController.ScriptName = codeController.name;
            }

            if (string.IsNullOrEmpty(codeController.PrefabFolder))
            {
                var setting = CodeGenSetting.Load();
                codeController.PrefabFolder = setting.PrefabDir;
            }
        }

        public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();

            {
                GUILayout.BeginVertical("box");
                GUILayout.Label("代码生成配置", BigTitleStyle.Value);
                {
                    GUILayout.BeginHorizontal();
                    GUILayout.Label("命名空间:", GUILayout.Width(100));
                    codeController.Namespace = GUILayout.TextArea(codeController.Namespace);
                    GUILayout.EndHorizontal();
                }
                {
                    GUILayout.BeginHorizontal();
                    GUILayout.Label("脚本名称:", GUILayout.Width(100));
                    codeController.ScriptName = GUILayout.TextArea(codeController.ScriptName);
                    GUILayout.EndHorizontal();
                }
                {
                    GUILayout.BeginHorizontal();
                    GUILayout.Label("继承:", GUILayout.Width(100));
                    codeController.BaseName = GUILayout.TextArea(codeController.BaseName);
                    GUILayout.EndHorizontal();
                }
                {
                    GUILayout.BeginHorizontal();
                    GUILayout.Label("脚本目录:", GUILayout.Width(100));
                    codeController.ScriptsFolder = GUILayout.TextArea(codeController.ScriptsFolder);
                    if (GUILayout.Button("...", GUILayout.Width(30)))
                    {
                        var folderPath = Application.dataPath.Replace("Assets", codeController.ScriptsFolder);
                        folderPath = EditorUtility.OpenFolderPanel("Select Folder", folderPath, string.Empty);
                        codeController.ScriptsFolder = folderPath.Replace(Application.dataPath, "Assets");
                    }

                    GUILayout.EndHorizontal();
                }
                EditorGUILayout.Space();
                EditorGUILayout.LabelField("请将要生成脚本的文件夹拖到下边区域 或 自行填写目录到上一栏中");
                {
                    var sfxPathRect = EditorGUILayout.GetControlRect();
                    sfxPathRect.height = 50;
                    GUI.Box(sfxPathRect, string.Empty);

                    EditorGUILayout.LabelField(string.Empty, GUILayout.Height(30));

                    if ((Event.current.type == EventType.DragUpdated || Event.current.type == EventType.DragPerform)
                        && sfxPathRect.Contains(Event.current.mousePosition))
                    {
                        //改变鼠标的外表
                        DragAndDrop.visualMode = DragAndDropVisualMode.Copy;

                        if (Event.current.type == EventType.DragPerform)
                        {
                            DragAndDrop.AcceptDrag();

                            if (null != DragAndDrop.paths && 0 < DragAndDrop.paths.Length)
                            {
                                var path = DragAndDrop.paths[0];
                                Debug.Log(path);

                                codeController.ScriptsFolder = path;

                                AssetDatabase.SaveAssets();
                                AssetDatabase.Refresh();
                                EditorSceneManager.MarkSceneDirty(SceneManager.GetActiveScene());
                            }
                        }

                        Event.current.Use();
                    }
                }
                {
                    GUILayout.BeginHorizontal();
                    codeController.GeneratePrefab = GUILayout.Toggle(codeController.GeneratePrefab, "生成Prefab");
                    GUILayout.EndHorizontal();

                    if (codeController.GeneratePrefab)
                    {
                        {
                            GUILayout.BeginHorizontal();
                            GUILayout.Label("Prefab目录:", GUILayout.Width(100));
                            codeController.PrefabFolder = GUILayout.TextArea(codeController.PrefabFolder);
                            if (GUILayout.Button("...", GUILayout.Width(30)))
                            {
                                var folderPath = Application.dataPath.Replace("Assets", codeController.PrefabFolder);
                                folderPath = EditorUtility.OpenFolderPanel("Select Folder", folderPath, string.Empty);
                                codeController.PrefabFolder = folderPath.Replace(Application.dataPath, "Assets");
                            }

                            GUILayout.EndHorizontal();
                        }
                    }
                }
                EditorGUILayout.Space();
                if (null == codeController.GetComponent<Binds>())
                {
                    if (GUILayout.Button("添加 Binds", GUILayout.Height(30)))
                    {
                        codeController.gameObject.AddComponent<Binds>();
                        EditorUtility.SetDirty(codeController.gameObject);
                        EditorSceneManager.MarkSceneDirty(codeController.gameObject.scene);
                    }
                }

                var filePath = $"{codeController.ScriptsFolder}/{codeController.ScriptName}.cs";
                if (File.Exists(filePath))
                {
                    var scriptAsset = AssetDatabase.LoadAssetAtPath<MonoScript>(filePath);
                    if (GUILayout.Button("打开脚本", GUILayout.Height(30)))
                    {
                        AssetDatabase.OpenAsset(scriptAsset);
                    }

                    if (GUILayout.Button("选择脚本", GUILayout.Height(30)))
                    {
                        Selection.activeObject = scriptAsset;
                    }
                }
                else
                {
                    // TODO::
                }

                if (GUILayout.Button("生成代码", GUILayout.Height(30)))
                {
                    CodeGen.Generate(codeController);
                    GUIUtility.ExitGUI();
                }

                GUILayout.EndVertical();
            }
        }
    }
}